package mate.task.odin;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Random;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.style.StyleSpan;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
/**
 * The list of items that the user has saved
 * @author Chris
 *
 */
public class ToDoListActivity extends Activity{
		
	private UserAccount user;
	private UserDatabase db;
	private ArrayList<ToDoItem> list;
	LinearLayout layout, zoneHead;
	LinearLayout dateRight;
	TextView dateTop, dateBottom;
	LinearLayout wow;
	ObjectOutputStream outputStream;
	Random rand;

	
	/**
	 * The Create activity for Android
	 * Creates the initial interface
	 */
	public void onCreate(Bundle savedInstanceState){
		
		super.onCreate(savedInstanceState);
		
		// Removes the top title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.todolist);

		ImageView plus = (ImageView) findViewById(R.id.plus);
		plus.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent itemCreate = new Intent("mate.task.odin.TODOITEMCREATEACTIVITY");
				startActivity(itemCreate);
			}
		});
		final EditText input = new EditText(this);
		Display d = getWindowManager().getDefaultDisplay();
		Point sze = new Point();
		d.getSize(sze);
		db = UserDatabase.getDatabaseInstance();
		user = db.getCurrentUser();
		list = user.getList().getItemList();
		
		layout = (LinearLayout) findViewById(R.id.rowList);
		zoneHead = (LinearLayout) findViewById(R.id.zoneHead);

		if(user.getZone() == 0)
		{
			zoneHead.setBackgroundColor(0xFF99CA3C);
		}
		if(user.getZone() == 1)
			zoneHead.setBackgroundColor(0xFFE02F2f);
		Spinner spinner = (Spinner) findViewById(R.id.spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.choose_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
		spinner.setAdapter(adapter);
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
		
		
		
		

	}
	
	
	
	public void onPause() {
		super.onPause();
	}
	
	/**
	 * The resume activity for Android
	 * Builds the list on Resume
	 */
	public void onResume() {
		super.onResume();
	}
	
	public void refreshList(final int x, final Object y){
		
		switch(x) {
		case 0: list = user.getList().filterByCompletion(false);
				break;
		case 1: list = user.getList().filterByCategory("PERSONAL");
				break;
		case 2: list = user.getList().filterByCategory("SCHOOL");
				break;
		case 3: list = user.getList().filterByCategory("WORK");
				break;
		case 4: list = user.getList().filterByDate((String) y);
				break;
		case 5: list = user.getList().filterByLocation((String)y);
				break;
		case 6: list = user.getList().filterByCompletion(true);
				break;
		
		}
		layout.removeAllViews();
		LinearLayout xpLay = (LinearLayout) findViewById(R.id.xpLay);
		xpLay.removeAllViews();
		LinearLayout textLay = new LinearLayout(this);
		TextView v1 = new TextView(this);
		TextView v2 = new TextView(this);
		ImageView v3 = new ImageView(this);
		// Generates the refreshed list
				Point size = new Point();

				LinearLayout textLayout;
				ImageView square;
				TextView taskName, taskDate, taskTags;
				ImageView swipe;
				Display display = getWindowManager().getDefaultDisplay();
				display.getSize(size);
				
				for (int i = 0; i < list.size(); i++){
					LinearLayout lin = new LinearLayout(this);
					layout.addView(lin, size.x , (size.y)/8);
					final ToDoItem item = list.get(i);
					lin.setOnClickListener(new View.OnClickListener(){

						public void onClick(View arg0) {
							Bundle b = new Bundle();
							b.putSerializable("item", item);
							Intent intent = new Intent("mate.task.odin.TODOITEMACTIVITY");
							intent.putExtras(b);
							startActivity(intent);
						}
						
					});
					lin.setTag("lin" + i);
					lin.setOrientation(LinearLayout.HORIZONTAL);
					square = new ImageView(this);
					square.setTag("check" + i);

					final String s = (String) square.getTag();
					final int j = Integer.parseInt(Character.toString(s.charAt(5)));
					
					if(user.getZone() == 0){
						if (i%2 == 0){
							lin.setBackgroundColor(0xFFD8EAB4);
							if (list.get(j).isCompleted()){
								square.setImageResource(R.drawable.checked);
							}
							else{
								square.setImageResource(R.drawable.unchecked);
							}
						}
						else{
							lin.setBackgroundColor(0xFFCEE4A0);
							if (list.get(j).isCompleted()){
								square.setImageResource(R.drawable.checked);
							}
							else{
								square.setImageResource(R.drawable.unchecked);
							}
						}
					}
					if(user.getZone() == 1){
						if (i%2 == 0){
							lin.setBackgroundColor(0xFFF5C9C9);
							if (list.get(j).isCompleted()){
								square.setImageResource(R.drawable.checked);
							}
							else{
								square.setImageResource(R.drawable.unchecked);
							}
						}
						else{
							lin.setBackgroundColor(0xFFFF8787);
							if (list.get(j).isCompleted()){
								square.setImageResource(R.drawable.checked);
							}
							else{
								square.setImageResource(R.drawable.unchecked);
							}
						}
					}

					lin.addView(square);
					square.setPadding(10, 30, 0, 0);
					

					square.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(final View v) {
							// TODO Auto-generated method stub
							
							if (!list.get(j).isCompleted()){
								list.get(j).complete();
								user.addXP();
								layout.removeAllViews();
								
							}
							else{
								list.get(j).undoComplete();
							}
							refreshList(x, y);
						}

					});
					
					
					lin.addView(textLayout = new LinearLayout(this), new LinearLayout.LayoutParams(470	, LinearLayout.LayoutParams.FILL_PARENT));
					textLayout.setOrientation(LinearLayout.VERTICAL);
					textLayout.setPadding(12, 10, 0, 0);
					
					textLayout.addView(taskName = new TextView(this));
					taskName.setText(list.get(i).getName(), TextView.BufferType.SPANNABLE);
					Spannable str = (Spannable) taskName.getText();
					str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, taskName.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					taskName.setText(str);
					taskName.setTextSize(20);
					taskName.setTextColor(0xff231F20);
					
					taskName.setPadding(0, 17, 0, 0);
					
					
					textLayout.addView(taskTags = new TextView(this));
					taskTags.setText("Tags: " + list.get(i).getTags());
					taskTags.setTextSize(14);
					taskTags.setPadding(0, -7, 0, 0);
					taskTags.setTextColor(0xff231f20);
					
						
					lin.addView(dateRight = new LinearLayout(this));
					dateRight.setOrientation(LinearLayout.VERTICAL);
					dateRight.addView(dateTop = new TextView(this));
					dateTop.setText(list.get(i).getDate().dayOfWeek());
					dateTop.setTextColor(0xff333333);
					dateTop.setGravity(0x01);
					dateTop.setTextSize(18);
					dateRight.setPadding(0, 15, 0, 0);
					dateRight.addView(dateBottom = new TextView(this));
					dateBottom.setText(list.get(i).getDate().getMonth() + "/" + list.get(i).getDate().getDay(), TextView.BufferType.SPANNABLE);
					Spannable str2 = (Spannable) dateBottom.getText();
					str2.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, dateBottom.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					dateBottom.setText(str2);
					dateBottom.setTextSize(24);
					dateBottom.setTextColor(0xff333333);
					dateBottom.setPadding(0, -10, 0, 0);
					
									
					
				}
				textLay.setOrientation(LinearLayout.VERTICAL);
				v1.setText("ZONE " + (user.getZone() + 1) + ":", TextView.BufferType.SPANNABLE);
				v2.setText(user.getZoneName(), TextView.BufferType.SPANNABLE);
				Spannable str3 = (Spannable) v1.getText();
				Spannable str4 = (Spannable) v2.getText();
				str3.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, v1.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				str4.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, v2.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				v1.setText(str3);
				v2.setText(str4);
				v1.setTextColor(0xFF333333);
				v2.setTextColor(0xFF000000);
				textLay.addView(v1);
				textLay.addView(v2);
				textLay.setPadding(16, 20, 0, 0);
				xpLay.addView(textLay);
				TextView newText = new TextView(this);
				newText.setTextColor(0xFF000000);
				newText.setTextSize(24);
				newText.setGravity(Gravity.CENTER_VERTICAL);
				newText.setPadding(40, 25, 0, 0);
				String xpStr = String.valueOf("XP: " + user.getXP());
				newText.setText(xpStr);
				Button b = new Button(this);
				b.setText("Fight");			
				b.setGravity(Gravity.CENTER);
				b.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						rand = new Random();
						int xpChange = user.getXP()/10;
						
						int randomNum = rand.nextInt(10) + 1;						
						if(randomNum <= xpChange){
							Intent i = new Intent("mate.task.odin.WINACTIVITY");
							startActivity(i);
							finish();
						}
						
						
						
						
						
					}
				});
				xpLay.addView(newText);
				LayoutParams lp = new LinearLayout.LayoutParams(300, 100);
				lp.setMargins(60, 0, 0, 0);
				xpLay.addView(b, lp);
				if(user.getZone() == 0)
					xpLay.setBackgroundColor(0xFF99CA3C);
				if(user.getZone() == 1)
					xpLay.setBackgroundColor(0xFFE02F2F);
			
				
	}
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		

	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	      Toast.makeText(parent.getContext(), "Filtering By " +
	          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
	      	if(pos == 4)
	      	{
	      		final EditText input2 = new EditText(ToDoListActivity.this);
	            AlertDialog.Builder alert = new AlertDialog.Builder(ToDoListActivity.this);
                alert.setTitle("Date To Filter By");
                alert.setMessage("Input date as MM/DD/YYYY");
                alert.setView(input2);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        
                        public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                refreshList(4,input2.getText().toString());
                        }
                });
                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                
                        }
                });
                alert.show();

	      	}
	      	else{
	      		refreshList(pos, "");
	      	}
	    }

	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	 public void onStop(){
	    	super.onStop();
	 
	 }

	 public void onDestroy(){
		 super.onDestroy();
		 String filename = "user_db.txt";
	        try {
	            
	            outputStream = new ObjectOutputStream(new FileOutputStream(filename));
	            outputStream.reset();
	         
	            outputStream.writeObject(db);
	            
	            
	        } catch (FileNotFoundException ex) {
	            ex.printStackTrace();
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        } finally {
	            //Close the ObjectOutputStream
	            try {
	                if (outputStream != null) {
	                    outputStream.flush();
	                    outputStream.close();
	                }
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	        finish();
	    }
	@Override
	 public boolean dispatchKeyEvent(KeyEvent event){
		if(event.getKeyCode() == (KeyEvent.KEYCODE_BACK)){
			Intent d = new Intent("mate.task.odin.TASKMATEACTIVITY");
			startActivity(d);
			finish();
			return true;
		}
		return false; 
	 }
	 }


